"""
Artificitial Neural Network
"""
import csv
from itertools import *
import operator

from Tkinter import *

class Synapse:
    def __init__(self,input=0,weight=0):
        self.input,self.weight = input,weight
        self.enable = True
    def query(self):
        return self.input*self.weight
        
class Neuron:
    weights,thresh = None, None
    guiInfo = {'color':'grey',
               'pos':[0,0]}
    def __init__(self,weights=None,thresh=None):
        self.weights = weights or self.weights
        self.thresh = thresh or self.thresh

        # connections
        self.outbound,self.inbound = [],[]
        
        self.guiInfo = Neuron.guiInfo
        self.guiInfo.update(self.__class__.guiInfo)
    def setup(self,inputs):
        pass
    def test(self,inputs):
        a = sum(imap(operator.mul,self.weights,inputs))
        if a>=self.thresh:
            return 1
        return 0

class AndNeuron(Neuron):
    guiInfo = {'color':'yellow'}
    def setup(self,inputs):
        numInputs = len(inputs)
        self.weights = [1,]*numInputs
        self.thresh = sum(self.weights)

class OrNeuron(Neuron):
    guiInfo = {'color':'blue'}
    def setup(self,inputs):
        numInputs = len(inputs)
        self.weights = [1,]*numInputs
        self.thresh = 1

class NotNeuron(Neuron):
    guiInfo = {'color':'magenta'}
    weights = [-1]
    thresh = 0

class InputNeuron(Neuron):
    pass

class NeuronPainter:
    def draw(self,neuron,canvas,x,y,width):
        id = canvas.create_oval(x-width,y-width,x+width,y+width)
        neuron.guiInfo['id'] = id
        return id
    

class NetworkApp(Frame):
    def __init__(self,parent,**kw):
        Frame.__init__(self,parent,**kw)

        self.canvas = Canvas(self,bd=2,relief='sunken',bg='white')
        self.canvas.bind('<ButtonPress-1>',self.event_buttonPress1)
        self.canvas.bind('<ButtonRelease-1>',self.event_buttonRelease1)
        self.canvas.bind('<B1-Motion>',self.event_motion1)
        self.canvas.bind('<ButtonPress-3>',self.event_buttonPress3)
        self.canvas.bind('<ButtonRelease-3>',self.event_buttonRelease3)
        self.canvas.bind('<B3-Motion>',self.event_motion3)
        self.canvas.bind('<Motion>',self.event_motion)

        self.canvas.pack(side='top',expand=1,fill='both')
        self.pack(expand=1,fill='both')

    def event_buttonPress1(self,event):
        x,y = event.x,event.y
    def event_buttonRelease1(self,event):
        x,y = event.x,event.y
    def event_buttonPress3(self,event):
        x,y = event.x,event.y
    def event_buttonRelease3(self,event):
        x,y = event.x,event.y
    def event_motion(self,event):
        x,y = event.x,event.y
    def event_motion1(self,event):
        x,y = event.x,event.y
        print 'Button 1',x,y
    def event_motion3(self,event):
        x,y = event.x,event.y
        print 'Button 3',x,y


if __name__=='__main__':
    root = Tk()
    netApp = NetworkApp(root)
    root.mainloop()
